import { deepClone } from '@/utils'
import BasicLayout from '@yang/layouts/index.vue'

/**
 * 根据path路径获取matched
 * @param routes 菜单routes
 * @param path 路径
 * @returns {*} matched
 */
export function handleMatched(routes: any, path: string) {
  const arr = routes.filter((route: any) =>
    (route?.childrenPathList || []).includes(path)
  )
  return arr.flatMap((route: any) => {
    return route.children
      ? [route, ...handleMatched(route.children, path)]
      : [route]
  })
}

function getChilderPath(arr: any, path: string) {
  const paths = deepClone(arr).map((el: any) => {
    let nextPaht: any = ''
    if (el.path.includes('/')) {
      nextPaht = el.path
    } else {
      nextPaht = path === '/' ? `${path}${el.path}` : `${path}/${el.path}`
    }
    if (el?.children && el.children.length > 0) {
      return getChilderPath(el.children, nextPaht)
    } else {
      return {
        paths: [nextPaht],
        names: [el.name]
      }
    }
  })
  return {
    paths: JSON.parse(JSON.stringify(paths))
      .map((el: any) => {
        return el.paths
      })
      .flat(),
    names: JSON.parse(JSON.stringify(paths))
      .map((el: any) => {
        return el.names
      })
      .flat()
  }
}
/**
 * 将权限路由转换成vue路由
 * @param routes - 权限路由
 * @param path - 权限路由
 * @description 所有多级路由都会被转换成二级路由
 */
export function transformAuthRouteToVueRoutes(routes: any, path?: string) {
  return routes.map((el: any) => {
    let nextPaht: any = ''
    if (el.path.includes('/')) {
      nextPaht = el.path
    } else {
      nextPaht = path === '/' ? `${path}${el.path}` : `${path}/${el.path}`
    }
    if (el.component === 'Layout') {
      el.component = BasicLayout
    } else {
      const modules: Record<string, () => Promise<unknown>> = import.meta.glob([
        '../views/*.{vue,tsx}',
        '../views/*/*.{vue,tsx}',
        '../views/*/*/*.{vue,tsx}',
        '../views/*/*/*/*.{vue,tsx}'
      ])
      el.component = modules[`../${el.component}.vue`]
    }
    if (el.children && el.children.length > 0) {
      el.children = transformAuthRouteToVueRoutes(el.children, nextPaht)
      const childerInfo = getChilderPath(el.children, el.path)
      el.childrenPathList = childerInfo.paths
      el.childrenNameList = childerInfo.names
    } else {
      el.childrenPathList = [nextPaht]
      el.childrenNameList = [el.name]
    }
    return el
  })
}

/**
 * 根据name查询某一条下的childer
 * */
export function findChildrenByName(routes, name) {
  for (const route of routes) {
    if (route.name === name) {
      return route.children || []
    }
    if (route.children) {
      const children = findChildrenByName(route.children, name)
      if (children.length > 0) {
        return children
      }
    }
  }
  return []
}
